package com.gq.anhlaicuaemnhe;

import java.io.IOException;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.res.AssetManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.text.InputType;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.webkit.WebView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.ads.AdRequest;
import com.google.ads.AdView;
import com.gq.utils.MyViewPager;
import com.gq.utils.NetworkState;
import com.rtst.widget.actionbar.ActionBarActivity;

public class ReaderActivity extends ActionBarActivity implements OnTouchListener {

	private MyViewPager viewPager;
	private int mPosition;
	private AdView adView;
	private Handler mHandler;
	private ImageView nextBtn, prevBtn;
	private TextView pageNum;
	public static int totalHtmlFiles = 0;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.reader_scr);
		new NetworkState(ReaderActivity.this).check();
		mHandler = new Handler();
		totalHtmlFiles = countHtmlFilesInAsset();
//		mPosition = getIntent().getExtras().getInt("POSITION");
		viewPager = (MyViewPager) findViewById(R.id.viewPager);
		viewPager.setPagingEnable(false);
		adView = (AdView) findViewById(R.id.adView);
		pageNum = (TextView) findViewById(R.id.pageNum);
		final ReaderAdapter adapter = new ReaderAdapter();
		viewPager.setAdapter(adapter);
		
		nextBtn = (ImageView) findViewById(R.id.btnNext);
		prevBtn = (ImageView) findViewById(R.id.btnPrevious);
		nextBtn.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				mHandler.removeCallbacks(mHideButtonRun);
				mHandler.postDelayed(mHideButtonRun, 3000);
				if (mPosition<adapter.getCount()-1) viewPager.setCurrentItem(mPosition+1);
			}
		});
		prevBtn.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				mHandler.removeCallbacks(mHideButtonRun);
				mHandler.postDelayed(mHideButtonRun, 3000);
				if (mPosition>0) viewPager.setCurrentItem(mPosition-1);
			}
		});
		
		viewPager.setOnPageChangeListener(new OnPageChangeListener() {
			
			@Override
			public void onPageSelected(int position) {
				updateButtonState(position, adapter);
//				setLastPage(position);
				if (position>0) {
					pageNum.setVisibility(View.VISIBLE);
					pageNum.setText(String.format("Trang %d/%d", position, totalHtmlFiles));
				} else {
					pageNum.setVisibility(View.GONE);
				}
				mPosition = position;
			}
			
			@Override
			public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
			}
			
			@Override
			public void onPageScrollStateChanged(int position) {
			}
		});
		viewPager.setCurrentItem(getLastPage());
		updateButtonState(0, adapter);
	}
	
	public int countHtmlFilesInAsset() {
		AssetManager assetmgr = getAssets();
		int count = 0;
		try {
			String[] files = assetmgr.list("");
			for (String f : files) {
				if (f.matches("\\d+\\.html")) count++;
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return count;
	}
	
	public void setLastPage(int pos) {
		SharedPreferences sharePreference = getPreferences(MODE_PRIVATE);
		Editor editor = sharePreference.edit();
		editor.putInt("lastvisit", pos);
		editor.commit();
	}
	
	public int getLastPage() {
		SharedPreferences sharePreference = getPreferences(MODE_PRIVATE);
		return sharePreference.getInt("lastvisit", 0);
	}
	
	public void updateButtonState(int pos, ReaderAdapter adapter) {
		if (!adapter.canGoNext(pos)) { nextBtn.setVisibility(View.GONE); } else {
			nextBtn.setVisibility(View.VISIBLE);
		}
		if (!adapter.canGoPrev(pos)) prevBtn.setVisibility(View.GONE); else {
			prevBtn.setVisibility(View.VISIBLE);
		}
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		adView.loadAd(new AdRequest());
		mHandler.postDelayed(mHideButtonRun, 3000);
	}

	@Override
	protected void onDestroy() {
		if (adView != null) adView.destroy();
		super.onDestroy();
	}
	
	private Runnable mHideButtonRun = new Runnable() {
		public void run() {
			nextBtn.setVisibility(View.GONE);
			prevBtn.setVisibility(View.GONE);
			pageNum.setVisibility(View.GONE);
		}
	};
	

	private class ReaderAdapter extends PagerAdapter {

		private int MAX_PAGE = totalHtmlFiles + 1;
		
		@Override
		public int getCount() {
			return MAX_PAGE;
		}
		
		public boolean canGoNext(int currentPos) {
			return currentPos < MAX_PAGE;
		}
		
		public boolean canGoPrev(int currentPos) {
			return currentPos > 0;
		}
		
		public String getItem(int position) {
			try {
				return String.format("%d.html", position);
			} catch(Exception e) {
			}
			return null;
		}

		@Override
		public boolean isViewFromObject(View view, Object object) {
			return view == (View) object;
		}

		@Override
		public void destroyItem(View container, int position, Object object) {
			((ViewPager) container).removeView((View) object);
		}

		@Override
		public Object instantiateItem(View container, int position) {
			
			if (position == 0) {
				LayoutInflater mInflate = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				ViewGroup viewGroup = (ViewGroup) mInflate.inflate(R.layout.intro_scr, null, false);
				((ViewPager) container).addView(viewGroup);
				viewGroup.setOnTouchListener(ReaderActivity.this);
				return viewGroup;
			}
			WebView webView = new WebView(ReaderActivity.this);
			webView.setOnTouchListener(ReaderActivity.this);
			String item = getItem(position);
			if (item != null) {
				webView.loadUrl("file:///android_asset/"+item);
			}
			((ViewPager) container).addView(webView);
			return webView;
		}
		
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater menuInflater = getMenuInflater();
		menuInflater.inflate(R.menu.read, menu);
		return super.onCreateOptionsMenu(menu);
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			//Toast.makeText(this, "Tapped home", Toast.LENGTH_SHORT).show();
			break;
		
		case R.id.menu_info:
			startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://search?q=pub:Viet Android JSC")));
			break;
		
		case R.id.menu_gotopage:
			AlertDialog.Builder gotoBuilder = new AlertDialog.Builder(this);
			gotoBuilder.setInverseBackgroundForced(true);
			gotoBuilder.setMessage("NHẬP SỐ TRANG");
			final EditText edtPgNum = new EditText(this);
			edtPgNum.setInputType(InputType.TYPE_CLASS_NUMBER);
			edtPgNum.setImeOptions(EditorInfo.IME_ACTION_GO);
			gotoBuilder.setView(edtPgNum);
			gotoBuilder.setPositiveButton("Goto", new DialogInterface.OnClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int which) {
					if (edtPgNum.getText().length()>0) {
						int position = Integer.parseInt(edtPgNum.getText().toString());
						if (position>0 && position<viewPager.getAdapter().getCount()) viewPager.setCurrentItem(position);
						dialog.dismiss();
					}
				}
			});
			gotoBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int which) {
					dialog.dismiss();
				}
			});
			final Dialog dlg;
			dlg = gotoBuilder.create();
			dlg.show();
			edtPgNum.setOnEditorActionListener(new TextView.OnEditorActionListener() {
				
				@Override
				public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
					if (actionId == EditorInfo.IME_ACTION_GO) {
						if (edtPgNum.getText().length()>0) {
							int position = Integer.parseInt(edtPgNum.getText().toString());
							if (position>0 && position<viewPager.getAdapter().getCount()) viewPager.setCurrentItem(position);
							if (dlg != null) dlg.dismiss();
						}
						return true;
					}
					return false;
				}
			});
			break;
			
		case R.id.menu_save:
			AlertDialog.Builder builder = new AlertDialog.Builder(ReaderActivity.this);
			builder.setMessage("Bạn muốn lưu lại trang hiện tại?")
			.setCancelable(true)
			.setPositiveButton("Có", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					setLastPage(mPosition);
					dialog.cancel();
				}
			})
			.setNegativeButton("Không", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					dialog.cancel();
				}
			});
			AlertDialog alertDialog = builder.create();
			alertDialog.show();
			break;
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	public boolean onTouch(View v, MotionEvent evt) {
		final int action = evt.getAction();
		switch(action & MotionEvent.ACTION_MASK) {
			case MotionEvent.ACTION_DOWN:
				nextBtn.setVisibility(View.VISIBLE);
				prevBtn.setVisibility(View.VISIBLE);
				pageNum.setVisibility(View.VISIBLE);
				break;
			case MotionEvent.ACTION_UP:
				mHandler.removeCallbacks(mHideButtonRun);
				mHandler.postDelayed(mHideButtonRun, 2000);
				break;
		}
		return false;
	}

	@Override
	public void onBackPressed() {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setMessage("Bạn muốn đóng ứng dụng ?")
		.setCancelable(true)
		.setPositiveButton("Có", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				onDestroy();
				System.runFinalizersOnExit(true);
				System.exit(0);
			}
		})
		.setNegativeButton("Không", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.cancel();
			}
		});
		AlertDialog alertDialog = builder.create();
		alertDialog.show();
	}
	
	
}
